﻿<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>WebSockets客户端示例</title>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script>
</head>
<script>
var webSocket;
   var str="aporhjbmvncjrovmbxvzzoeclolmqlpvsdffgfgf";
    function ss(a,b){
        var fanhui="";
        for(var i=0;i<b;i++){
            var aa= Math.floor(Math.random()*(str.length));
            fanhui+= str.substring(aa,aa+1);
        }
      return fanhui;
    }
    var usrName= ss(1,6);
    $(function(){
    		$("#usrName").text(usrName);
    });
function connect()
{
    try
    {
    	 
        var readyState = new Array("正在连接","已建立连接","正在关闭连接","已关闭连接");
        var host = "ws:localhost:62918/Handler1.ashx?user=" + usrName;
        webSocket = new WebSocket(host);
        var message = document.getElementById("message");
        message.innerHTML +="<p>Socket状态：" + readyState[webSocket.readyState] + "</p>";
        webSocket.onopen = function()
        {
            message.innerHTML += "<p>Socket状态：" + readyState[webSocket.readyState] + "</p>";
        }
        webSocket.onmessage = function(msg)
        {
            message.innerHTML +="<p>接收信息：" + msg.data + "</p>";
        }
        webSocket.onclose=function()
        {
            message.innerHTML +="<p>Socket状态：" + readyState[webSocket.readyState] + "</p>";
        }
    }
    catch(exception)
    {
        message.innerHTML += "<p>有错误发生</p>";
    }
}
function send()
{
    var sendUser=$("#sendUser").val();
    var text = document.getElementById("text").value;
    var sendData ={ SendUser: usrName, ToUser: sendUser, Content: text };
    var sendDataStr = JSON.stringify(sendData);
    var message = document.getElementById("message");
    if (sendData == "")
    {
        message.innerHTML += "<p>请输入一些文字</p>";
        return ;
    }
    try
    {
        webSocket.send(sendDataStr);
        message.innerHTML += "<p>发送数据：" +text + "</p>";
    }
    catch(exception)
    {
        message.innerHTML += "<p>发送数据出错</p>";
    }
    document.getElementById("text").value="";
}
function disconnect()
{
    webSocket.close();
}
</script>
<body>
<h1>WebSocket客户端示例</h1>
<div id="message"></div>
<p>请输入一些文字</p>
<p>您的用户名:<label id="usrName"></label></p>
发送给：
<input id="sendUser" type="text"  style="width:55px;"/>
内容:
<input id="text" type="text" style="width:200px;" >
<button id="connect" onClick="connect();">建立连接</button>
<button id="send" onClick="send();">发送数据</button>
<button id="disconnect" onClick="disconnect();">断开连接</button>

</body>
</html>